package middleware.p2p.log;

import java.net.URL;

import middleware.p2p.global.monitor.GlobalMonitor;
import middleware.p2p.global.monitor.GlobalMonitorService;

import org.apache.log4j.helpers.Transform;
import org.apache.log4j.spi.LoggingEvent;
import org.apache.log4j.xml.XMLLayout;

/**
 * 	Layout del logger del sistema middleware
 */
public class MiddlewareMonitorLayout extends XMLLayout {
	/**
	 * 	Istanza del Web Service di logging a cui mandare i log
	 */
	private GlobalMonitor globalMonitor;
	public MiddlewareMonitorLayout() {
		this(null);		
	}
	public MiddlewareMonitorLayout(URL globalMonitorWsdl) {
		super();
		GlobalMonitorService serv=new GlobalMonitorService(globalMonitorWsdl);
		this.globalMonitor=serv.getGlobalMonitorPort();
	}
	public String format(LoggingEvent event) {
		if (event.getMessage() instanceof SerializableXmlString) {
			StringBuffer buf=new StringBuffer();
			buf.append("<log4j:event logger=\"");
			buf.append(Transform.escapeTags(event.getLoggerName()));
			buf.append("\" timestamp=\"");
			buf.append(event.timeStamp);
			buf.append("\" level=\"");
			buf.append(Transform.escapeTags(String.valueOf(event.getLevel())));
			buf.append("\" thread=\"");
			buf.append(Transform.escapeTags(event.getThreadName()));
			buf.append("\">\r\n");
			buf.append("<log4j:message>");			
			Transform.appendEscapingCDATA(buf,((SerializableXmlString)event.getMessage()).toXmlString());
			buf.append("</log4j:message>\r\n");
			buf.append("</log4j:event>\r\n\r\n");
			return buf.toString();
		} else if (event.getMessage() instanceof XmlSerializable){
			XmlSerializable msg=(XmlSerializable)event.getMessage();
			if (msg instanceof MiddlewareMonitorEvent) {
				((MiddlewareMonitorEvent)msg).setTimestamp(event.getTimeStamp());
				if (this.globalMonitor!=null) {
					MiddlewareMonitorEvent mwEvent=(MiddlewareMonitorEvent)msg;
					this.globalMonitor.pushAsync(mwEvent.getType(), mwEvent);
				}
			}
			return msg.toXmlString()+"\n\n";
		}  else {
			return "";
		}
		/*if (event.getMessage() instanceof MiddlewareLogEvent) {
			MiddlewareLogEvent mwEvent= (MiddlewareLogEvent)event.getMessage();
			StringBuilder sb= new StringBuilder();
			sb.append("<ant_mw:logevent>\n");
			sb.append("<ant_mw:log_cid>"+this.componentID+"</ant_mw:log_cid>\n");
			sb.append("<ant_mw:log_vclock>"+mwEvent.getVclock().toXmlString()+"</ant_mw:log_vclock>\n");
			sb.append("<ant_mw:log_timestamp>"+event.getTimeStamp()+"</ant_mw:log_timestamp>\n");
			sb.append("<ant_mw:log_description>"+mwEvent.getDescription()+"</ant_mw:log_description>\n");
			sb.append("</ant_mw:logevent>\n\n");
			return sb.toString();			
		} else {
			//System.out.println("=============> "+event.getMessage());
			return "";
		}*/
	}

}
